
from typing import List

class Solution:
    def minPathSum(self, grid: List[List[int]]) -> int:
        if not grid or not grid[0]:
            return 0
        
        m, n = len(grid), len(grid[0])
        
        # 初始化 dp 数组，dp[i][j] 表示从左上角到 (i,j) 的最小路径和
        dp = [[0] * n for _ in range(m)]
        
        dp[0][0] = grid[0][0]
        
        # 初始化第一列，只能从上方走下来
        for i in range(1, m):
            dp[i][0] = dp[i-1][0] + grid[i][0]
        
        # 初始化第一行，只能从左边走过来
        for j in range(1, n):
            dp[0][j] = dp[0][j-1] + grid[0][j]
        
        # 状态转移，当前位置的最小路径和为上方和左方的较小值加当前格子值
        for i in range(1, m):
            for j in range(1, n):
                dp[i][j] = min(dp[i-1][j], dp[i][j-1]) + grid[i][j]
        
        return dp[m-1][n-1]
